<template>
  <el-card>
    <template #header>添加账号</template>

    <!-- 主题内容 -->
    <div>
      <el-button type="danger" size="mini" class="del-more" @click="handleDelete(false)">批量删除</el-button>
      <el-table
        :data="tableData"
        style="width: 100%"
        size="small"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80px"></el-table-column>
        <el-table-column prop="username" label="账号名称" width="120px"></el-table-column>
        <el-table-column prop="group_id" label="用户权限" width="120px">
          <template v-slot="{ row }">
            <el-tag v-if="row.group_id === 1">超级管理员</el-tag>
            <el-tag type="warning" v-else>普通管理员</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 2.0 分页处理 -->
      <div class="block">
        <span class="demonstration">调整每页显示条数</span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="pageSize"
          layout="total,sizes, prev, pager, next"
          :total="total"
        ></el-pagination>
      </div>
      <!-- 3.0 -->
      <el-dialog title="账号编辑" :visible.sync="dialogVisible" width="400px" @close="handleClosse">
        <el-form
          :model="accountForm"
          :rules="rules"
          ref="ruleForm"
          label-width="80px"
          class="demo-ruleForm"
          size="small"
        >
          <el-form-item label="账号名称" prop="username">
            <el-input
              type="text"
              v-model="accountForm.username"
              autocomplete="off"
              prefix-icon="iconfont icon-yonghu1"
            ></el-input>
          </el-form-item>

          <el-form-item label="账号权限" prop="group_id">
            <el-select v-model="accountForm.group_id" placeholder="请选择">
              <el-option label="普通管理员" value="2"></el-option>
              <el-option label="超级管理员" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editAccount">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import { userList, delUser, editUser } from '@/api/users.js'

export default {
  data() {
    var validateAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名或者账号'))
      } else {
        callback()
      }
    }
    var validateUsers = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择用户权限'))
      } else {
        callback()
      }
    }
    return {
      currentPage: 1,
      pageSize: 5,
      total: 0,
      tableData: [],
      multipleSelection: [],
      dialogVisible: false,
      curItem: '',
      // 1.0 数据对象
      accountForm: {
        username: '',
        group_id: ''
      },
      // 2.0 规则对象
      rules: {
        username: [{ validator: validateAccount, trigger: 'blur' }],
        group_id: [{ validator: validateUsers, trigger: 'change' }]
      },
      flag: true
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      // 获取本地数据的 token 和 member_id
      const users = JSON.parse(localStorage.getItem('users') || '{}')
      const { data, count } = await userList({
        member_id: users.member_id,
        access_token: users.access_token,
        page: this.currentPage,
        limit: this.pageSize
      })
      // console.log(data)
      this.tableData = data
      this.total = count
    },
    handleEdit(o) {
      // 解决了下拉框回写失败，因为数据格式问题
      // o.group_id = o.group_id + ''  修改了别人的数据
      // console.log(index, row)
      // 当前数据比较简单，可以使用JSON的方式
      this.accountForm = JSON.parse(JSON.stringify(o))
      this.accountForm.group_id = this.accountForm.group_id + ''
      this.dialogVisible = true
    },
    handleDelete(id) {
      let ids = ''
      if (id) {
        // 单项删除
        ids = id
      } else {
        // 批量删除
        // filter 会把满足条件的该项返回  map 把每一项的指定内容返回
        const arr = this.multipleSelection.map(item => item.id)
        // console.log(arr,1)
        ids = arr.join()
      }

      // 如果当前的列表没有任何数据了，直接改变页码
      if (this.tableData.length <= 1) {
        this.currentPage--
      }

      // console.log(index, row)
      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // this.$message({
          // 当用户点击确定删除的时候，发请求
          // 获取本地数据的 token 和 member_id
          // type: 'success',
          // message: '删除成功!'
          const users = JSON.parse(localStorage.getItem('users') || '{}')
          const { code, msg } = await delUser({
            member_id: users.member_id,
            access_token: users.access_token,
            ids: ids
          })
          if (code === 1) {
            this.$message.success(msg)
            this.getUserList()
          } else {
            this.$message.error(msg)
          }
          // console.log(data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleClosse() {
      this.$refs.ruleForm.resetFields()
    },
    editAccount() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // alert('submit!') 弹框提示
          // 验证通过，可以添加用户了
          // const token = window.localStorage.getItem('token')
          const users = window.localStorage.getItem('users') || '{}'
          const token = JSON.parse(users).access_token
          const { code, msg } = await editUser({
            member_id: JSON.parse(users).member_id,
            access_token: token,
            username: this.accountForm.username,
            group_id: this.accountForm.group_id - 0,
            id: this.accountForm.id
          })

          if (code === 1) {
            this.$message.success(msg)
            this.getUserList()
            // setTimeout(() => {
            //   this.$router.push('/users/list')
            // }, 1500)
          } else {
            this.$message.error(msg)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
      this.dialogVisible = false
    },
    batchDel() {},
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getUserList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  height: 100%;
  border: none;

  .del-more {
    margin: 5px 0 10px 0;
  }

  .el-input {
    width: 199px;
  }
}
</style>
